﻿angular.module('app.allinfo', [])
.config(['$routeProvider', function ($routeProvider) {
    $routeProvider
        .when('/allinfo', {
            templateUrl: 'app/allcontactinfo/allinfo.tpl.html',
            controller: 'allinfoCtrl',
            resolve: {
            }
        });
}])

.controller('allinfoCtrl', ['$scope', 'allinfoProxy', '$interval', 'baseDataProxy', 'siteProxy', 'APPSETTING','permissionProxy',
    function ($scope, allinfoProxy, $interval, baseDataProxy, siteProxy, APPSETTING, permissionProxy) {

        $scope.floatMenuOwner = ['allinfoCtrl'];

        $scope.allinfoList = {
            data: 'allinfos',
            columnDefs: [
                    { field: 'legalEntity', displayName: 'Legal Entity', pinnedLeft: true, width: '100' },
                    { field: 'customerNum', displayName: 'Customer Code', pinnedLeft: true, width: '100' },
                    { field: 'customerName', displayName: 'Customer Name', pinnedLeft: true, width: '100' },
                    { field: 'billGroupCode', displayName: 'Factory Group Code', width: '100' },
                    { field: 'billGroupName', displayName: 'Factory Group Name', width: '100' },
                    { field: 'team', displayName: 'Team', width: '100' },
                    { field: 'collector', displayName: 'Collector', width: '100' },
                    { field: 'country', displayName: 'Country', width: '100' },
                    { field: 'class', displayName: 'Customer Class', width: '100' },
                    { field: 'contact', displayName: 'Contactors', width: '100' },
                    { field: 'arBalanceAmtPeroid', displayName: 'AR balance Period', width: '100', cellFilter: 'number:2', type: 'number' },
                    { field: 'balanceAmt', displayName: 'Current Balance', width: '100', cellFilter: 'number:2', type: 'number' },
                    //{ field: 'paidAmt', displayName: 'Paied', width: '80', cellFilter: 'number:2', type: 'number' },
                    { field: 'overDue90Amt', displayName: 'Over 90 days', width: '100', cellFilter: 'number:2', type: 'number' },
                    { field: 'adjustedOver90', displayName: 'Forecast adjusted over90', width: '100', cellFilter: 'number:2', type: 'number' },
                    { field: 'ptpAmt', displayName: 'PTP', width: '100', cellFilter: 'number:2', type: 'number' },
                    { field: 'brokenPTPAmt', displayName: 'Broken PTP', width: '100', cellFilter: 'number:2', type: 'number' },
                    { field: 'disputeAmt', displayName: 'Dispute', width: '100', cellFilter: 'number:2', type: 'number' },
                    { field: 'soaDate', displayName: 'SOA Finsh Date', width: '100',cellFilter: 'date:\'yyyy-MM-dd\'' },
                    { field: 'secondDate', displayName: '2nd Reminder Finsh Date', width: '100', cellFilter: 'date:\'yyyy-MM-dd\'' },
                    { field: 'finalDate', displayName: 'Final reminder Finsh Date', width: '100', cellFilter: 'date:\'yyyy-MM-dd\'' },
                    { field: 'specialNotes', displayName: 'Special Notes', width: '100' },
                    { field: 'paymentTerm', displayName: 'Payment Term', width: '100' }
                    
                    //{ field: 'unapplidPayment', displayName: 'Unapplid Payment', width: '80', cellFilter: 'number:2', type: 'number' }
            ],

            onRegisterApi: function (gridApi) {
                //set gridApi on scope
            $scope.gridApi = gridApi;

        }
        }

        var filstr = "";

        $scope.maxSize = 10; //paging display max
        $scope.slexecute = 15;  //init paging size(ng-model)
        $scope.iperexecute = 15;   //init paging size(parameter)
        $scope.curpexecute = 1;     //init page
        $scope.totalNum = "";
        $scope.levelList = [
                    { "id": 15, "levelName": '15' },
                    { "id": 500, "levelName": '500' },
                    { "id": 1000, "levelName": '1000' },
                    { "id": 2000, "levelName": '2000' },
                    { "id": 5000, "levelName": '5000' },
                    { "id": 999999, "levelName": 'ALL' }
        ];
        allinfoProxy.allinfoPaging($scope.curpexecute, $scope.iperexecute, "&invoiceState=&invoiceTrackState=&invoiceNum=&soNum=&poNum=&invoiceMemo=" + filstr, function (list)
        {
            //$scope.totalItems = list[0].count;
            $scope.allinfos = list[0].results;
            $scope.ttexecute = list[0].count;
            $scope.totalNum = list[0].count;
            //float menu 加载 
            $scope.calculate($scope.curpexecute, $scope.iperexecute, list[0].results.length);
            $scope.$broadcast("FLOAT_MENU_REFRESH", $scope.floatMenuOwner[0]);
        }, function (error) { alert(error);});
        
        //paging size change
        $scope.pschangeexecute = function (slexecute) {
            var index = 1;
            $scope.curpexecute = 1;     //init page
            filstr = buildFilter();
            allinfoProxy.allinfoPaging(index, slexecute, filstr, function (list) {
                $scope.iperexecute = slexecute;
                $scope.allinfos = list[0].results;
                $scope.ttexecute = list[0].count;
                $scope.totalNum = list[0].count;
                $scope.calculate($scope.curpexecute, $scope.iperexecute, list[0].results.length);
            });
        };

        //paging change
        $scope.executepChanged = function () {

            var index = $scope.curpexecute;
            filstr = buildFilter();
            allinfoProxy.allinfoPaging(index, $scope.iperexecute, filstr, function (list) {
                $scope.allinfos = list[0].results;
                $scope.ttexecute = list[0].count;
                $scope.totalNum = list[0].count;
                $scope.calculate($scope.curpexecute, $scope.iperexecute, list[0].results.length);
            }, function (error) {
                alert(error);
            });
        };

        $scope.calculate = function (currentPage, itemsperpage, count) {
            if (count == 0) {
                $scope.fromItem = 0;
            } else {
                $scope.fromItem = (currentPage - 1) * itemsperpage + 1;
            }
            $scope.toItem = (currentPage - 1) * itemsperpage + count;
        }

        //*************************Send Soa *****************************************s
        $scope.openAllList = function () {

            var strids = []; //= "";
            var strSites = [];
            //var ccount = 0;
            if ($scope.gridApi.selection.getSelectedRows()) {
                angular.forEach($scope.gridApi.selection.getSelectedRows(), function (rowItem) {
                    strids.push(rowItem.customerNum + ";" + rowItem.legalEntity);
                });
            }
            if (strids == "") {
                alert("Please choose 1 customer at least .")
            } else {
                window.open('#/allcontactinfo/allaccount/' + strids + '/');
            }

        }

        //*************************aging search *****************************************s
        //openfilter
        var isShow = 0; //0:hide;1:show
        var baseFlg = true;
        $scope.showCollector = false;
        $scope.openFilter = function () {

            //*************************aging filter base binding*****************************s
            if (baseFlg) {
                baseDataProxy.SysTypeDetails("006,004,029,005", function (res) {
                    angular.forEach(res, function (r) {
                        $scope.cusclass = r["006"];
                        $scope.istatuslist = r["004"];
                        $scope.invoiceTrackStates = r["029"];
                        $scope.cusstatus = r["005"];
                    });
                });

                //Legal Entity DropDownList binding
                siteProxy.Site("", function (legal) {
                    $scope.legallist = legal;
                });

                permissionProxy.getCurrentUser("dummy", function (user) {
                    if (user.actionPermissions.indexOf('alldataforsupervisor') >= 0) {
                        $scope.showCollector = true;
                        //Collector List
                        permissionProxy.query({ 'getCollectList': 'dummy' }, function (res) {
                            $scope.collectorList = res;
                        })
                    }
                })
            }
            //*************************aging filter base binding*****************************e

            if (isShow == 0) {
                $("#divAgingSearch").show();
                isShow = 1;
                baseFlg = false;
            } else if (isShow == 1) {
                $("#divAgingSearch").hide();
                isShow = 0;
                baseFlg = false;
            }
        }

        //reset Search conditions
        $scope.resetSearch = function () {
            filstr = "";
            $scope.custCode = "";
            $scope.custName = "";
            $scope.class = "";
            $scope.status = "";
            $scope.legal = "";
            $scope.billGroupCode = "";
            $scope.billGroupName = "";
            $scope.states = "";
            $scope.trackStates = "";
            $scope.invoiceNum = "";
            $scope.soNum = "";
            $scope.poNum = "";
            $scope.invoiceMemo = "";
        }

        $scope.searchCollection = function () {

            filstr = buildFilter();

            var index = 1;
            $scope.curpexecute = 1;     //init page
            allinfoProxy.allinfoPaging(index, $scope.iperexecute, filstr, function (list) {
                $scope.allinfos = list[0].results;
                $scope.ttexecute = list[0].count;
                $scope.totalNum = list[0].count;
                //$scope.calculate($scope.curpdone, $scope.iperdone, list[0].results.length);
                $scope.calculate($scope.curpexecute, $scope.iperexecute, list[0].results.length);
            });

        }
        $scope.export = function () {
            //window.location = APPSETTING['serverUrl'] + '/api/contactCustomer?exportlist=1';
            window.location = APPSETTING['serverUrl'] + '/api/allinfo?' +
                'cCode=' + $scope.custCode + '&cName=' + $scope.custName + '&level=' + $scope.class + '&bCode=' + $scope.billGroupCode + '&bName=' + $scope.billGroupName + '&legal=' + $scope.legal +
                '&state=' + $scope.states + '&tstate=' + $scope.trackStates + '&iNum=' + $scope.invoiceNum + '&pNum=' + $scope.poNum + '&sNum=' + $scope.soNum + '&memo=' + $scope.memo + '&oper=' + $scope.collector;
                
        }
        buildFilter = function () {
            var filterStr = "";
            if ($scope.custCode) {
                if (filterStr == "") {
                    filterStr += "&$filter=(contains(CustomerNum,'" + encodeURIComponent($scope.custCode) + "'))";
                } else {
                    filterStr += " and (contains(CustomerNum,'" + encodeURIComponent($scope.custCode) + "'))";
                }
            }

            if ($scope.custName) {
                if (filterStr == "") {
                    filterStr += "&$filter=(contains(CustomerName,'" + encodeURIComponent($scope.custName) + "'))"
                } else {
                    filterStr += " and (contains(CustomerName,'" + encodeURIComponent($scope.custName) + "'))"
                }
            }

            if ($scope.class) {
                if (filterStr == "") {
                    filterStr += "&$filter=(Class eq '" + $scope.class + "')";
                } else {
                    filterStr += " and (Class eq '" + $scope.class + "')";
                }
            }

            //if ($scope.status) {
            //    if (filterStr == "") {
            //        filterStr += "&$filter=(CusStatus eq '" + $scope.status + "')";
            //    } else {
            //        filterStr += " and (CusStatus eq '" + $scope.status + "')";
            //    }
            //}

            //bill Grop Code
            if ($scope.billGroupCode) {
                if (filterStr == "") {
                    filterStr += "&$filter=(contains(BillGroupCode,'" + encodeURIComponent($scope.billGroupCode) + "'))";
                } else {
                    filterStr += " and (contains(BillGroupCode,'" + encodeURIComponent($scope.billGroupCode) + "'))";
                }
            }
            //bill Grop Code
            if ($scope.billGroupName) {
                if (filterStr == "") {
                    filterStr += "&$filter=(contains(BillGroupName,'" + encodeURIComponent($scope.billGroupName) + "'))";
                } else {
                    filterStr += " and (contains(BillGroupName,'" + encodeURIComponent($scope.billGroupName) + "'))";
                }
            }

            if ($scope.legal) {
                if (filterStr == "") {
                    filterStr += "&$filter=(LegalEntity eq '" + $scope.legal + "')"
                } else {
                    filterStr += " and (LegalEntity eq '" + $scope.legal + "')";
                }
            }

            if ($scope.collector) {
                if (filterStr == "") {
                    filterStr += "&$filter=(Collector eq '" + $scope.collector + "')"
                } else {
                    filterStr += " and (Collector eq '" + $scope.collector + "')";
                }
            }

            
                //invoice Memo
                if ($scope.invoiceMemo) {
                    filterStr = "&invoiceMemo=" + $scope.invoiceMemo + filterStr;
                } else {
                    filterStr = "&invoiceMemo=" + filterStr;
                }

                //invoice PO
                if ($scope.poNum) {
                    filterStr = "&poNum=" + $scope.poNum + filterStr;
                } else {
                    filterStr = "&poNum=" + filterStr;
                }

                //invoice SO
                if ($scope.soNum) {
                    filterStr = "&soNum=" + $scope.soNum + filterStr;
                } else {
                    filterStr = "&soNum=" + filterStr;
                }

                //invoice Num
                if ($scope.invoiceNum) {
                    filterStr = "&invoiceNum=" + $scope.invoiceNum + filterStr;
                } else {
                    filterStr = "&invoiceNum=" + filterStr;
                }

                //if ($scope.legal) {
                //    filterStr = "&legalEntity=" + $scope.legal + filterStr;
                //} else {
                //    filterStr = "&legalEntity=" + filterStr;
                //}

                //invoice Track States
                if ($scope.trackStates) {
                    filterStr = "&invoiceTrackState=" + $scope.trackStates + filterStr;
                } else {
                    filterStr = "&invoiceTrackState=" + filterStr;
                }

                //invoice states
                if ($scope.states) {
                    filterStr = "&invoiceState=" + $scope.states + filterStr;
                } else {
                    filterStr = "&invoiceState=" + filterStr;
                }
                
            return filterStr;
        };

    }]);